<template>
  <view class="wx-login">
    <image src="/static/logo.png" class="wx-login-logo" />

    <button v-if="!state.isAgree" class="wx-login-btn" @click="wxLoginClick"> 手机号快捷登录 </button>

    <button v-if="hasPhone && state.isAgree" class="wx-login-btn" @click="wxLoginClick"> 手机号快捷登录 </button>

    <button
      v-if="!hasPhone && state.isAgree"
      open-type="getPhoneNumber|agreePrivacyAuthorization"
      @getphonenumber="getPhoneNumber"
      class="wx-login-btn"
      >手机号快捷登录</button
    >

    <!-- 用户协议的勾选 -->
    <view class="wx-login-agree">
      <label class="wx-login-agree-label">
        <uni-icons type="circle" size="24" style="margin-right: 5rpx;" v-if="!state.isAgree" color="#C61323" @click="onAgreeChange(true)"></uni-icons>
        <uni-icons type="checkbox-filled" size="24" style="margin-right: 5rpx;" v-if="state.isAgree" color="#C61323" @click="onAgreeChange(false)"></uni-icons>
        <view class="wx-login-agree-text">
          我已阅读并遵守
          <view class="tcp-text" @tap.stop="onProtocol('用户协议')"> 《用户协议》 </view>
          <view class="wx-login-agree-text">与</view>
          <view class="tcp-text" @tap.stop="onProtocol('隐私协议')"> 《隐私协议》 </view>
        </view>
      </label>
    </view>
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app';

  import { WX_LOGIN_INFO } from '@/utils/constants.js';

  import { setItem, getItem } from '@/utils/storage.js';

  import { showToast, showLoading, hideLoading, toPage } from '@/utils/app.js';

  import { getWxCodeInfo, wxLogin } from '@/api/wechat.js';

  import { useUserInfoStore } from '@/stores/user';
  const userInfoStore = useUserInfoStore();

  /**是否有手机号 */
  const hasPhone = ref(false);

  onLoad((options) => {
    getCodeReq(function (code) {
      if (code) {
        getWxCodeInfoReq(code, function (data) {
          hasPhone.value = data.hasPhone || false;
          setItem(WX_LOGIN_INFO, data);
        });
      }
    });
  });

  //  获取微信信息
  const getWxCodeInfoReq = (code, callback) => {
    getWxCodeInfo({ code }).then((res) => {
      const data = res.data;
      userInfoStore.serviceAccessType = res.data.serviceAccessType + '';
      userInfoStore.enterpriseWechatId = res.data.enterpriseWechatId;
      userInfoStore.enterpriseWechatLink = res.data.enterpriseWechatLink;
      callback(data);
    });
  };

  // 获取Code
  const getCodeReq = (callback) => {
    uni.login({
      success: function (res) {
        const code = res.code;
        callback(code);
      },
    });
  };

  //  微信一键登录
  const getPhoneNumber = (e) => {
    if (!state.isAgree) return showToast('请勾选我已阅读并遵守');
    const iv = e.detail.iv;
    const encryptedData = e.detail.encryptedData;
    // 获取用户信息
    wx.getUserInfo({
      withCredentials: true, // 非必填, 默认为true
      success: function (res) {
        // 校验session
        checkSession(res, iv, encryptedData);
      },
      fail: function (err) {
        showToast('获取微信用户信息失败');
      },
    });
  };

  // 校验session
  const checkSession = (userInfo, iv, encryptedData) => {
    wx.checkSession({
      success: function (res) {
        const wxLoginInfo = getItem(WX_LOGIN_INFO);
        if (wxLoginInfo.session_key) {
          const sessionKey = wxLoginInfo.sessionKey;
          const openid = wxLoginInfo.openid;
          const unionid = wxLoginInfo.unionId;
          wxLoginReq(
            {
              sessionKey,
              openid,
              unionid,
            },
            userInfo,
            iv,
            encryptedData
          );
        } else {
          getSessionKey(userInfo, iv, encryptedData);
        }
      },
      fail: function (res) {
        getSessionKey(userInfo, iv, encryptedData);
      },
    });
  };

  // 获取sessionKey
  const getSessionKey = (userInfo, iv, encryptedData) => {
    getCodeReq(function (code) {
      getWxCodeInfoReq(code, function (data) {
        setItem(WX_LOGIN_INFO, data);
        wxLoginReq(data, userInfo, iv, encryptedData);
      });
    });
  };

  // 微信登录
  const wxLoginClick = () => {
    if (!state.isAgree) return showToast('请勾选我已阅读并遵守');
    getCodeReq(function (code) {
      getWxCodeInfoReq(code, function (data) {
        setItem(WX_LOGIN_INFO, data);
        wxLoginReq(data, {}, '', '');
      });
    });
  };

  // 微信登录请求
  const wxLoginReq = (wxSession, userInfo, iv, encryptedData) => {
    showLoading('');
    wxLogin({
      sessionKey: wxSession.sessionKey,
      iv,
      encryptedData,
      openid: wxSession.openid,
      unionId: wxSession.unionId,
    })
      .then((res) => {
        hideLoading();
        handleLogin(res);
      })
      .catch((err) => {
        hideLoading();
        showToast(err.msg);
      });
  };

  // 处理登录信息
  const handleLogin = (res) => {
    showToast('微信登录成功');
    userInfoStore.wxLogin(res.data);
    setTimeout(function () {
      uni.switchTab({
        url: '/pages/index/mall',
      });
    }, 1000);
  };

  const state = reactive({
    isAgree: false,
  });
  // 勾选协议
  const onAgreeChange = (flag) => {
    state.isAgree = flag
  }

  // 查看协议
  const onProtocol = (title) => {
    toPage('/pages/user/richtext?title=' + title)
  };
</script>

<style scoped lang="scss">
  page {
    background: #ffffff;
  }

  .wx-login {
    display: flex;
    flex-direction: column;
    align-items: center;

    .wx-login-logo {
      width: 180rpx;
      height: 180rpx;
      margin-top: 200rpx;
    }

    .wx-login-btn {
      width: 654rpx;
      height: 92rpx;
      margin-top: 80rpx;
      border-radius: 16rpx;
      background: linear-gradient(138.98deg, #cb3d3d 0.5%, #a11012 100.24%);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #ffffff;
      font-family: PingFang SC;
      font-weight: 600;
      font-size: 32rpx;
    }

    .wx-login-agree {
      margin: 1.5rem auto 0;

      .wx-login-agree-label {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
      }

      .wx-login-agree-text {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        font-size: 24rpx;

        .tcp-text {
          color: #C61323;
        }
      }
    }
  }
</style>
